import React, { useState, useEffect, useMemo } from 'react';
import {
  Table, Card, Tag, Button, Input, Select, DatePicker, Space, Drawer, Typography,
  Row, Col, Statistic, Progress, Tabs, Timeline, Alert, Badge, Tooltip,
  Switch, Modal, Form, notification, Divider, List, Avatar, Collapse,
  TreeSelect, Checkbox, Radio, Spin, Empty, Result, message
} from 'antd';
import {
  SearchOutlined, ReloadOutlined, BugOutlined, ClockCircleOutlined,
  WarningOutlined, InfoCircleOutlined, DashboardOutlined, UserOutlined,
  GlobalOutlined, CodeOutlined, SettingOutlined, BellOutlined,
  BarChartOutlined, LineChartOutlined, PieChartOutlined, FilterOutlined,
  ExportOutlined, ShareAltOutlined, EyeOutlined, PlayCircleOutlined,
  ThunderboltOutlined, SafetyCertificateOutlined, RobotOutlined
} from '@ant-design/icons';
import { useParams, history } from '@umijs/max';
import type { ColumnsType } from 'antd/es/table';
import ErrorTrendChart from './components/ErrorTrendChart'; // 添加这行导入
import {
  getErrorLogs,
  getDashboardStats,
  getErrorTrend,
  getRealTimeErrors,
  type ErrorLog,
  type DashboardStats,
  type ErrorTrendData,
  type ErrorLogParams
} from '@/services/errorLogs';
import './index.less';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Text, Paragraph, Title } = Typography;
const { TabPane } = Tabs;
const { Panel } = Collapse;

// 趋势数据接口
interface TrendDataPoint {
  time: string;
  errorCount: number;
  errorRate: number;
  severity: 'low' | 'medium' | 'high' | 'critical';
  type: string;
}

// 在组件开始处添加解析 User Agent 的函数
const parseUserAgent = (userAgent: string) => {
  if (!userAgent) {
    return {
      os: '未知系统',
      browser: '未知浏览器',
      device: '未知设备',
      isMobile: false,
      deviceModel: null,
      osVersion: null
    };
  }

  const ua = userAgent.toLowerCase();
  let os = '未知系统';
  let browser = '未知浏览器';
  let device = '桌面设备';
  let isMobile = false;
  let deviceModel = null;
  let osVersion = null;

  // 检测移动设备
  if (/mobile|android|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent)) {
    isMobile = true;
    device = '移动设备';
  }

  // 检测操作系统和版本
  if (/android/i.test(ua)) {
    os = 'Android';
    const androidMatch = userAgent.match(/Android ([\d\.]+)/);
    if (androidMatch) {
      osVersion = androidMatch[1];
    }
    device = '安卓设备';
    
    // 检测安卓设备型号
    const modelMatch = userAgent.match(/;\s*([^;)]+)\s*Build/);
    if (modelMatch) {
      deviceModel = modelMatch[1].trim();
    }
  } else if (/iphone/i.test(ua)) {
    os = 'iOS';
    device = 'iPhone';
    const iosMatch = userAgent.match(/OS ([\d_]+)/);
    if (iosMatch) {
      osVersion = iosMatch[1].replace(/_/g, '.');
    }
    
    // 检测iPhone型号
    if (/iPhone/i.test(userAgent)) {
      const iphoneMatch = userAgent.match(/iPhone OS ([\d_]+)/);
      if (iphoneMatch) {
        deviceModel = 'iPhone';
      }
    }
  } else if (/ipad/i.test(ua)) {
    os = 'iPadOS';
    device = 'iPad';
    const iosMatch = userAgent.match(/OS ([\d_]+)/);
    if (iosMatch) {
      osVersion = iosMatch[1].replace(/_/g, '.');
    }
    deviceModel = 'iPad';
  } else if (/windows/i.test(ua)) {
    os = 'Windows';
    if (/windows nt 10/i.test(ua)) osVersion = '10';
    else if (/windows nt 6.3/i.test(ua)) osVersion = '8.1';
    else if (/windows nt 6.2/i.test(ua)) osVersion = '8';
    else if (/windows nt 6.1/i.test(ua)) osVersion = '7';
  } else if (/mac os x/i.test(ua)) {
    os = 'macOS';
    const macMatch = userAgent.match(/Mac OS X ([\d_]+)/);
    if (macMatch) {
      osVersion = macMatch[1].replace(/_/g, '.');
    }
  } else if (/linux/i.test(ua)) {
    os = 'Linux';
  }

  // 检测浏览器
  if (/chrome/i.test(ua) && !/edge/i.test(ua)) {
    browser = 'Chrome';
    const chromeMatch = userAgent.match(/Chrome\/([\d\.]+)/);
    if (chromeMatch) {
      browser += ` ${chromeMatch[1]}`;
    }
  } else if (/firefox/i.test(ua)) {
    browser = 'Firefox';
    const firefoxMatch = userAgent.match(/Firefox\/([\d\.]+)/);
    if (firefoxMatch) {
      browser += ` ${firefoxMatch[1]}`;
    }
  } else if (/safari/i.test(ua) && !/chrome/i.test(ua)) {
    browser = 'Safari';
    const safariMatch = userAgent.match(/Version\/([\d\.]+)/);
    if (safariMatch) {
      browser += ` ${safariMatch[1]}`;
    }
  } else if (/edge/i.test(ua)) {
    browser = 'Edge';
    const edgeMatch = userAgent.match(/Edge\/([\d\.]+)/);
    if (edgeMatch) {
      browser += ` ${edgeMatch[1]}`;
    }
  } else if (/micromessenger/i.test(ua)) {
    browser = '微信浏览器';
    const wechatMatch = userAgent.match(/MicroMessenger\/([\d\.]+)/);
    if (wechatMatch) {
      browser += ` ${wechatMatch[1]}`;
    }
  }

  return {
    os: osVersion ? `${os} ${osVersion}` : os,
    browser,
    device,
    isMobile,
    deviceModel,
    osVersion
  };
};

const ErrorLogs: React.FC = () => {
  const { projectId } = useParams<{ projectId: string }>();
  
  // 将projectId转换为数字类型，添加验证 - 移到组件顶层
  const numericProjectId = useMemo(() => {
    if (!projectId) return null;
    const parsed = parseInt(projectId, 10);
    return isNaN(parsed) ? null : parsed;
  }, [projectId]);
  
  const [logs, setLogs] = useState<ErrorLog[]>([]);
    const [loading, setLoading] = useState(true);
  const [searchText, setSearchText] = useState('');
  const [levelFilter, setLevelFilter] = useState<string>('all');
  const [selectedLog, setSelectedLog] = useState<ErrorLog | null>(null);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('logs');
  const [dashboardStats, setDashboardStats] = useState<DashboardStats | null>(null);
  const [alertModalVisible, setAlertModalVisible] = useState(false);
  const [realTimeEnabled, setRealTimeEnabled] = useState(false);
  const [groupBy, setGroupBy] = useState('fingerprint');
  const [timeRange, setTimeRange] = useState('24h');
  const [selectedEnvironment, setSelectedEnvironment] = useState('all');
  
  // 趋势图相关状态
  const [trendData, setTrendData] = useState<TrendDataPoint[]>([]);
  const [chartLoading, setChartLoading] = useState(false);
  const [metric, setMetric] = useState('errorCount');
  const [selectedTrendData, setSelectedTrendData] = useState<TrendDataPoint | null>(null);
  const [trendDetailVisible, setTrendDetailVisible] = useState(false);

  // 获取趋势数据的函数
  const fetchTrendData = async (range: string, metricType: string) => {
    setChartLoading(true);
    try {
      console.log('请求参数:', { projectId, timeRange: range, metric: metricType });
      
      const data = await getErrorTrend({
        projectId,
        timeRange: range,
        metric: metricType
      });
      
      console.log('API返回数据:', data);
      
      // 检查数据是否为空或无效
      if (!data || !Array.isArray(data)) {
        console.warn('API返回数据格式异常:', data);
        setTrendData([]);
        message.warning('暂无趋势数据');
        return;
      }
      
      if (data.length === 0) {
        console.log('API返回空数据');
        setTrendData([]);
        message.info('当前时间范围内暂无错误数据');
        return;
      }
      
      // 处理后端返回的数据，添加severity字段
      const processedData = data.map(item => ({
        ...item,
        severity: item.errorCount >= 50 ? 'critical' as const : 
                 item.errorCount >= 20 ? 'high' as const : 
                 item.errorCount >= 5 ? 'medium' as const : 'low' as const,
        details: [] // 添加可选的details字段
      }));
      
      console.log('处理后的数据:', processedData);
      setTrendData(processedData);
      
    } catch (error) {
      console.error('获取趋势数据失败:', error);
      message.error(`获取趋势数据失败: ${error.message || '未知错误'}`);
      setTrendData([]);
    } finally {
      setChartLoading(false);
    }
  };

  // 添加实时数据更新函数
  const fetchRealTimeData = async () => {
    if (!realTimeEnabled) return;
    
    try {
      const response = await getRealTimeErrors(projectId);
      if (response.success && response.data.length > 0) {
        // 更新日志列表，添加新的错误到顶部
        setLogs(prevLogs => {
          const newLogs = response.data.filter(
            newLog => !prevLogs.some(existingLog => existingLog.id === newLog.id)
          );
          return [...newLogs, ...prevLogs].slice(0, 100); // 保持最多100条记录
        });
        
        // 刷新仪表板数据
        fetchDashboardStats();
      }
    } catch (error) {
      console.error('获取实时数据失败:', error);
    }
  };

  // 实时更新相关函数
  const startRealTimeUpdate = () => {
    // 启动实时更新逻辑
    console.log('启动实时更新');
  };

  const stopRealTimeUpdate = () => {
    // 停止实时更新逻辑
    console.log('停止实时更新');
  };

  useEffect(() => {
    fetchLogs();
    fetchDashboardStats();
    fetchTrendData();
  }, [projectId, timeRange, selectedEnvironment]);

  // 在useEffect中添加实时数据更新
  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    if (realTimeEnabled) {
      // 每30秒获取一次实时数据
      interval = setInterval(fetchRealTimeData, 30000);
    }
    
    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [realTimeEnabled, projectId]);

  // 实时数据更新
  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (realTimeEnabled) {
      interval = setInterval(() => {
        fetchLogs();
        fetchDashboardStats();
        fetchTrendData(timeRange, metric);
      }, 5000);
    }
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [realTimeEnabled, timeRange, metric]);

  const fetchLogs = async () => {
    if (!numericProjectId) {
      message.error('无效的项目ID');
      return;
    }
    
    setLoading(true);
    try {
      const params: ErrorLogParams = {
        project: numericProjectId.toString(), // 使用数字类型
        level: levelFilter === 'all' ? undefined : levelFilter,
        search: searchText || undefined,
        page: 1,
        page_size: 20,
        ordering: '-timestamp'
      };
      
      if (timeRange !== 'all') {
        const now = new Date();
        let startTime: Date;
        
        switch (timeRange) {
          case '1h':
            startTime = new Date(now.getTime() - 60 * 60 * 1000);
            break;
          case '24h':
            startTime = new Date(now.getTime() - 24 * 60 * 60 * 1000);
            break;
          case '7d':
            startTime = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
            break;
          case '30d':
            startTime = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
            break;
          default:
            startTime = new Date(now.getTime() - 24 * 60 * 60 * 1000);
        }
        
        params.start_time = startTime.toISOString();
        params.end_time = now.toISOString();
      }
      
      const response = await getErrorLogs(params);
      debugger
      if (response.success) {
        setLogs(response.data.results);
      } else {
        message.error('获取错误日志失败');
      }
    } catch (error) {
      console.error('获取错误日志失败:', error);
      message.error('获取错误日志失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchDashboardStats = async () => {
    if (!numericProjectId) return;
    
    try {
      console.log('正在获取仪表板数据，项目ID:', numericProjectId);
      const stats = await getDashboardStats(numericProjectId.toString());
      console.log('获取到的仪表板数据:', stats);
      setDashboardStats(stats);
      debugger
    } catch (error) {
      console.error('获取仪表板数据失败:', error);
      message.error('获取仪表板数据失败');
      // 设置默认数据以避免空白页面
      setDashboardStats({
        totalErrors: 0,
        errorRate: 0,
        affectedUsers: 0,
        avgResponseTime: 0,
        errorTrend: [],
        topErrors: [],
        browserStats: [],
        errorsByLevel: { error: 0, warning: 0, info: 0, debug: 0 }
      });
    }
  };

  // 渲染仪表板
  const renderDashboard = () => {
    if (!dashboardStats) {
      return (
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>正在加载仪表板数据...</div>
        </div>
      );
    }

    // 检查是否有数据
    const hasData = dashboardStats.totalErrors > 0;
    
    if (!hasData) {
      return (
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Empty 
            description="暂无错误日志数据"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          >
            <Button type="primary" onClick={fetchLogs}>
              刷新数据
            </Button>
          </Empty>
        </div>
      );
    }

    return (
      <div className="dashboard-container">
        {/* 关键指标卡片 */}
        <Row gutter={[16, 16]} className="stats-cards">
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="总错误数"
                value={dashboardStats.totalErrors}
                prefix={<BugOutlined />}
                valueStyle={{ color: '#cf1322' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="错误率"
                value={dashboardStats.errorRate}
                suffix="%"
                prefix={<WarningOutlined />}
                valueStyle={{ color: '#fa8c16' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="受影响用户"
                value={dashboardStats.affectedUsers}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="平均响应时间"
                value={dashboardStats.avgResponseTime}
                suffix="s"
                prefix={<ThunderboltOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 错误趋势图表 - 集成ErrorTrendChart组件 */}
        <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
          <Col xs={24} lg={16}>
            <ErrorTrendChart
              data={trendData}
              loading={chartLoading}
              height={300}
              realTimeEnabled={realTimeEnabled}
              onTimeRangeChange={(range) => {
                setTimeRange(range);
                fetchTrendData(range, metric);
              }}
              onMetricChange={(newMetric) => {
                setMetric(newMetric);
                fetchTrendData(timeRange, newMetric);
              }}
              onDataPointClick={(dataPoint) => {
                setSelectedTrendData(dataPoint);
                setTrendDetailVisible(true);
              }}
              onRealTimeToggle={(enabled) => {
                setRealTimeEnabled(enabled);
                if (enabled) {
                  startRealTimeUpdate();
                } else {
                  stopRealTimeUpdate();
                }
              }}
            />
          </Col>
          <Col xs={24} lg={8}>
            <Card title="错误级别分布" extra={<PieChartOutlined />}>
              <div className="level-distribution">
                <div className="level-item">
                  <Badge color="red" text={`错误: ${dashboardStats.errorsByLevel.error}`} />
                  <Progress percent={70} showInfo={false} strokeColor="red" />
                </div>
                <div className="level-item">
                  <Badge color="orange" text={`警告: ${dashboardStats.errorsByLevel.warning}`} />
                  <Progress percent={20} showInfo={false} strokeColor="orange" />
                </div>
                <div className="level-item">
                  <Badge color="blue" text={`信息: ${dashboardStats.errorsByLevel.info}`} />
                  <Progress percent={8} showInfo={false} strokeColor="blue" />
                </div>
                <div className="level-item">
                  <Badge color="gray" text={`调试: ${dashboardStats.errorsByLevel.debug}`} />
                  <Progress percent={2} showInfo={false} strokeColor="gray" />
                </div>
              </div>
            </Card>
          </Col>
        </Row>

        {/* Top错误和浏览器统计 */}
        <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
          <Col xs={24} lg={12}>
            <Card title="高频错误排行" extra={<BarChartOutlined />}>
              <List
                dataSource={dashboardStats.topErrors}
                renderItem={(item) => (
                  <List.Item>
                    <List.Item.Meta
                      title={<Text ellipsis style={{ width: 200 }}>{item.message}</Text>}
                      description={`出现 ${item.count} 次`}
                    />
                    <Tag color={item.trend === 'up' ? 'red' : item.trend === 'down' ? 'green' : 'blue'}>
                      {item.trend === 'up' ? '↑' : item.trend === 'down' ? '↓' : '→'}
                    </Tag>
                  </List.Item>
                )}
              />
            </Card>
          </Col>
          <Col xs={24} lg={12}>
            <Card title="浏览器分布" extra={<GlobalOutlined />}>
              <List
                dataSource={dashboardStats.browserStats}
                renderItem={(item) => (
                  <List.Item>
                    <List.Item.Meta
                      title={item.name}
                      description={`${item.count} 次错误`}
                    />
                    <div>
                      <Progress percent={item.percentage} size="small" />
                      <Text style={{ marginLeft: 8 }}>{item.percentage}%</Text>
                    </div>
                  </List.Item>
                )}
              />
            </Card>
          </Col>
        </Row>
      </div>
    );
  };

  // 渲染智能告警配置
  const renderAlertConfig = () => {
    return (
      <div className="alert-config">
        <Card title="告警规则配置" extra={<BellOutlined />}>
          <Form layout="vertical">
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item label="错误频率阈值">
                  <Input addonAfter="次/分钟" placeholder="10" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="响应时间阈值">
                  <Input addonAfter="秒" placeholder="3" />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item label="通知方式">
                  <Checkbox.Group>
                    <Checkbox value="email">邮件</Checkbox>
                    <Checkbox value="sms">短信</Checkbox>
                    <Checkbox value="webhook">Webhook</Checkbox>
                    <Checkbox value="push">推送</Checkbox>
                  </Checkbox.Group>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="静默期设置">
                  <Select placeholder="选择静默期">
                    <Option value="5">5分钟</Option>
                    <Option value="15">15分钟</Option>
                    <Option value="30">30分钟</Option>
                    <Option value="60">1小时</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Form.Item>
              <Button type="primary">保存告警配置</Button>
            </Form.Item>
          </Form>
        </Card>

        <Card title="AI异常检测" style={{ marginTop: 16 }} extra={<RobotOutlined />}>
          <Alert
            message="智能异常检测已启用"
            description="基于机器学习算法，自动识别异常错误模式和趋势变化"
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
          <Row gutter={16}>
            <Col span={8}>
              <Statistic title="检测到异常模式" value={3} suffix="个" />
            </Col>
            <Col span={8}>
              <Statistic title="预测准确率" value={94.5} suffix="%" />
            </Col>
            <Col span={8}>
              <Statistic title="误报率" value={2.1} suffix="%" />
            </Col>
          </Row>
        </Card>
      </div>
    );
  };

  // 渲染用户行为追踪
  const renderUserBehavior = () => {
    if (!selectedLog) {
      return (
        <div className="user-behavior">
          <Card title="用户行为分析" extra={<UserOutlined />}>
            <Empty 
              description="请从错误日志列表中选择一个错误查看详细的用户行为路径"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            >
              <Button type="primary" onClick={() => setActiveTab('logs')}>
                查看错误日志
              </Button>
            </Empty>
          </Card>
        </div>
      );
    }

    if (!selectedLog?.breadcrumbs || selectedLog.breadcrumbs.length === 0) {
      return <Empty description="暂无用户行为数据" />;
    }

    return (
      <div className="user-behavior">
        <Row gutter={[16, 16]}>
          <Col xs={24} lg={16}>
            <Card title="用户操作路径" extra={<UserOutlined />}>
              <Timeline>
                {selectedLog.breadcrumbs.map((crumb, index) => (
                  <Timeline.Item
                    key={index}
                    color={crumb.level === 'error' ? 'red' : crumb.level === 'warning' ? 'orange' : 'blue'}
                  >
                    <div className="breadcrumb-item">
                      <div className="breadcrumb-header">
                        <Text strong>{crumb.message}</Text>
                        <Text type="secondary" style={{ marginLeft: 8 }}>{crumb.timestamp}</Text>
                      </div>
                      <div style={{ marginTop: 4 }}>
                        <Tag color={crumb.level === 'error' ? 'red' : crumb.level === 'warning' ? 'orange' : 'blue'}>
                          {crumb.category}
                        </Tag>
                      </div>
                      {crumb.data && (
                        <Collapse size="small" style={{ marginTop: 8 }}>
                          <Panel header="详细数据" key="1">
                            <pre>{JSON.stringify(crumb.data, null, 2)}</pre>
                          </Panel>
                        </Collapse>
                      )}
                    </div>
                  </Timeline.Item>
                ))}
              </Timeline>
            </Card>
          </Col>
          
          <Col xs={24} lg={8}>
            <Card title="错误概览" extra={<BugOutlined />} style={{ marginBottom: 16 }}>
              <div className="error-overview">
                <div className="overview-item">
                  <Text strong>错误信息:</Text>
                  <Paragraph ellipsis={{ rows: 2, expandable: true }}>
                    {selectedLog.message}
                  </Paragraph>
                </div>
                <div className="overview-item">
                  <Text strong>发生时间:</Text>
                  <Text>{selectedLog.timestamp}</Text>
                </div>
                <div className="overview-item">
                  <Text strong>错误级别:</Text>
                  <Tag color={getLevelColor(selectedLog.level)}>
                    {selectedLog.level.toUpperCase()}
                  </Tag>
                </div>
                <div className="overview-item">
                  <Text strong>用户ID:</Text>
                  <Text>{selectedLog.userId || '匿名用户'}</Text>
                </div>
                <div className="overview-item">
                  <Text strong>会话ID:</Text>
                  <Text code>{selectedLog.sessionId}</Text>
                </div>
              </div>
            </Card>
            
            <Card title="用户环境" extra={<GlobalOutlined />}>
              <div className="user-environment">
                {selectedLog.user_agent && (() => {
                  const deviceInfo = parseUserAgent(selectedLog.user_agent);
                  return (
                    <>
                      <div className="env-item">
                        <Text strong>设备类型:</Text>
                        <Tag color={deviceInfo.isMobile ? 'orange' : 'blue'}>
                          {deviceInfo.device}
                        </Tag>
                      </div>
                      <div className="env-item">
                        <Text strong>操作系统:</Text>
                        <Text>{deviceInfo.os}</Text>
                      </div>
                      <div className="env-item">
                        <Text strong>浏览器:</Text>
                        <Text>{deviceInfo.browser}</Text>
                      </div>
                      {deviceInfo.deviceModel && (
                        <div className="env-item">
                          <Text strong>设备型号:</Text>
                          <Text>{deviceInfo.deviceModel}</Text>
                        </div>
                      )}
                    </>
                  );
                })()}
                <div className="env-item">
                  <Text strong>IP地址:</Text>
                  <Text>{selectedLog.ip_address}</Text>
                </div>
                <div className="env-item">
                  <Text strong>访问URL:</Text>
                  <Text code ellipsis={{ tooltip: selectedLog.url }}>
                    {selectedLog.url}
                  </Text>
                </div>
              </div>
            </Card>
          </Col>
        </Row>

        {selectedLog.performance && (
          <Card title="性能监控数据" style={{ marginTop: 16 }} extra={<DashboardOutlined />}>
            <Row gutter={16}>
              <Col span={6}>
                <Statistic
                  title="内存使用率"
                  value={selectedLog.performance.memoryUsage}
                  suffix="%"
                  valueStyle={{ color: selectedLog.performance.memoryUsage > 80 ? '#cf1322' : '#52c41a' }}
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="CPU使用率"
                  value={selectedLog.performance.cpuUsage}
                  suffix="%"
                  valueStyle={{ color: selectedLog.performance.cpuUsage > 70 ? '#cf1322' : '#52c41a' }}
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="页面加载时间"
                  value={selectedLog.performance.loadTime}
                  suffix="ms"
                  valueStyle={{ color: selectedLog.performance.loadTime > 2000 ? '#cf1322' : '#52c41a' }}
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="渲染时间"
                  value={selectedLog.performance.renderTime}
                  suffix="ms"
                  valueStyle={{ color: selectedLog.performance.renderTime > 100 ? '#cf1322' : '#52c41a' }}
                />
              </Col>
            </Row>
          </Card>
        )}
      </div>
    );
  };

  const getLevelColor = (level: string) => {
    switch (level) {
      case 'error': return 'red';
      case 'warning': return 'orange';
      case 'info': return 'blue';
      case 'debug': return 'gray';
      default: return 'default';
    }
  };

  const filteredLogs = logs.filter(log => {
    const matchesSearch = log.message.toLowerCase().includes(searchText.toLowerCase()) ||
                         log.source.toLowerCase().includes(searchText.toLowerCase());
    const matchesLevel = levelFilter === 'all' || log.level === levelFilter;
    const matchesEnv = selectedEnvironment === 'all' || log.environment.deployEnv === selectedEnvironment;
    return matchesSearch && matchesLevel && matchesEnv;
  });

  const columns: ColumnsType<ErrorLog> = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: 180,
      render: (timestamp) => (
        <div className="timestamp-cell">
          <ClockCircleOutlined style={{ marginRight: 4 }} />
          {timestamp}
        </div>
      )
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      width: 80,
      render: (level) => (
        <Tag color={getLevelColor(level)}>
          {level.toUpperCase()}
        </Tag>
      )
    },
    {
      title: '错误信息',
      dataIndex: 'message',
      key: 'message',
      ellipsis: true,
      render: (message, record) => (
        <div className="message-cell">
          <Text ellipsis={{ tooltip: message }}>{message}</Text>
          {record.count && record.count > 1 && (
            <Badge count={record.count} style={{ marginLeft: 8 }} />
          )}
        </div>
      )
    },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
      width: 200,
      ellipsis: true,
      render: (source) => (
        <Text code ellipsis={{ tooltip: source }}>{source}</Text>
      )
    },
    {
      title: '环境',
      dataIndex: 'user_agent',
      key: 'environment',
      width: 150,
      render: (userAgent, record) => {
        const deviceInfo = parseUserAgent(userAgent);
        
        if (!userAgent) {
          return <Tag color="default">未知环境</Tag>;
        }
        
        const { os, browser, device, isMobile, deviceModel } = deviceInfo;
        
        // 构建显示文本
        let displayText = device;
        if (isMobile && deviceModel) {
          displayText = deviceModel;
        }
        
        // 构建详细信息
        const detailInfo = [
          `操作系统: ${os}`,
          `浏览器: ${browser}`,
          `设备类型: ${device}`
        ];
        
        if (isMobile && deviceModel) {
          detailInfo.push(`设备型号: ${deviceModel}`);
        }
        
        // 根据设备类型选择颜色
        let tagColor = 'blue';
        if (isMobile) {
          if (os.includes('iOS')) {
            tagColor = 'purple';
          } else if (os.includes('Android')) {
            tagColor = 'green';
          } else {
            tagColor = 'orange';
          }
        }
        
        return (
          <Tooltip title={detailInfo.join('\n')} placement="topLeft">
            <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
              <Tag color={tagColor} size="small">
                {displayText}
              </Tag>
              {isMobile && (
                <Tag color="cyan" size="small">
                  📱 {os.split(' ')[0]}
                </Tag>
              )}
            </div>
          </Tooltip>
        );
      }
    },
    {
      title: '用户',
      dataIndex: 'userId',
      key: 'userId',
      width: 100,
      render: (userId) => userId ? (
        <Tooltip title={`用户ID: ${userId}`}>
          <Avatar size="small" icon={<UserOutlined />} />
        </Tooltip>
      ) : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            size="small"
            icon={<EyeOutlined />}
            onClick={() => {
              setSelectedLog(record);
              console.log(record)
              setDrawerVisible(true);
            }}
          >
            详情
          </Button>
          <Button 
            type="link" 
            size="small"
            icon={<PlayCircleOutlined />}
            onClick={() => {
              setSelectedLog(record);
              setActiveTab('behavior');
            }}
          >
            行为追踪
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div className="error-logs-container">
      {/* 动态背景 */}
      <div className="logs-background">
        <div className="particles"></div>
        <div className="grid-overlay"></div>
      </div>
      
      <div className="logs-content">
        <div className="logs-header">
          <div className="header-left">
            <h1>错误日志管理</h1>
            <Badge count={logs.length} style={{ backgroundColor: '#f50' }} />
          </div>
          <div className="header-actions">
            <Switch
              checked={realTimeEnabled}
              onChange={setRealTimeEnabled}
              checkedChildren="实时"
              unCheckedChildren="暂停"
            />
            <Button 
              icon={<ReloadOutlined />} 
              onClick={fetchLogs}
              loading={loading}
            >
              刷新
            </Button>
            <Button 
              type="primary"
              icon={<SettingOutlined />}
              onClick={() => setAlertModalVisible(true)}
            >
              告警配置
            </Button>
          </div>
        </div>

        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          className="main-tabs"
        >
        <TabPane tab={<span><DashboardOutlined />实时监控大屏</span>} key="dashboard">
          {renderDashboard()}
        </TabPane>
        
        <TabPane tab={<span><BugOutlined />错误日志列表</span>} key="logs">
          <Card className="filters-card">
            <Row gutter={[16, 16]}>
              <Col xs={24} sm={12} md={8}>
                <Input
                  placeholder="搜索错误信息或来源"
                  prefix={<SearchOutlined />}
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                />
              </Col>
              <Col xs={24} sm={12} md={4}>
                <Select
                  value={levelFilter}
                  onChange={setLevelFilter}
                  style={{ width: '100%' }}
                  placeholder="错误级别"
                >
                  <Option value="all">全部级别</Option>
                  <Option value="error">错误</Option>
                  <Option value="warning">警告</Option>
                  <Option value="info">信息</Option>
                  <Option value="debug">调试</Option>
                </Select>
              </Col>
              <Col xs={24} sm={12} md={4}>
                <Select
                  value={selectedEnvironment}
                  onChange={setSelectedEnvironment}
                  style={{ width: '100%' }}
                  placeholder="部署环境"
                >
                  <Option value="all">全部环境</Option>
                  <Option value="production">生产环境</Option>
                  <Option value="staging">预发布环境</Option>
                  <Option value="development">开发环境</Option>
                </Select>
              </Col>
              <Col xs={24} sm={12} md={6}>
                <Select
                  value={timeRange}
                  onChange={setTimeRange}
                  style={{ width: '100%' }}
                  placeholder="时间范围"
                >
                  <Option value="1h">最近1小时</Option>
                  <Option value="24h">最近24小时</Option>
                  <Option value="7d">最近7天</Option>
                  <Option value="30d">最近30天</Option>
                </Select>
              </Col>
              <Col xs={24} sm={12} md={4}>
                <Select
                  value={groupBy}
                  onChange={setGroupBy}
                  style={{ width: '100%' }}
                  placeholder="分组方式"
                >
                  <Option value="fingerprint">错误指纹</Option>
                  <Option value="source">错误来源</Option>
                  <Option value="user">用户</Option>
                  <Option value="browser">浏览器</Option>
                </Select>
              </Col>
            </Row>
          </Card>

          <Card className="logs-table-card">
            <Table
              columns={columns}
              dataSource={filteredLogs}
              rowKey="id"
              loading={loading}
              pagination={{
                pageSize: 20,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
              scroll={{ x: 1200 }}
            />
          </Card>
        </TabPane>
        
        <TabPane tab={<span><UserOutlined />用户行为追踪</span>} key="behavior">
          {renderUserBehavior()}
        </TabPane>
        
        <TabPane tab={<span><BellOutlined />智能告警</span>} key="alerts">
          {renderAlertConfig()}
        </TabPane>
        
        <TabPane tab={<span><LineChartOutlined />趋势分析</span>} key="trend">
          <ErrorTrendChart
            data={trendData}
            loading={chartLoading}
            height={500}
            realTimeEnabled={realTimeEnabled}
            onTimeRangeChange={(range) => {
              setTimeRange(range);
              fetchTrendData(range, metric);
            }}
            onMetricChange={(newMetric) => {
              setMetric(newMetric);
              fetchTrendData(timeRange, newMetric);
            }}
            onDataPointClick={(dataPoint) => {
              setSelectedTrendData(dataPoint);
              setTrendDetailVisible(true);
            }}
            onRealTimeToggle={(enabled) => {
              setRealTimeEnabled(enabled);
              if (enabled) {
                startRealTimeUpdate();
              } else {
                stopRealTimeUpdate();
              }
            }}
          />
        </TabPane>
        
        <TabPane tab={<span><BarChartOutlined />数据分析</span>} key="analytics">
          <Card title="错误关联分析" extra={<ShareAltOutlined />}>
            <Alert
              message="功能开发中"
              description="错误关联分析、用户群体分析、版本对比分析等功能正在开发中"
              type="info"
              showIcon
            />
          </Card>
        </TabPane>
        </Tabs>
      </div>
      
      {/* 错误详情抽屉 */}
      <Drawer
        title="错误详情"
        placement="right"
        width={800}
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
      >
        
        {selectedLog && (
          <div className="log-detail">
            <Tabs defaultActiveKey="basic">
              <TabPane tab="基本信息" key="basic">
                <div className="detail-section">
                  <div className="detail-item">
                    <strong>错误指纹:</strong>
                    <Text code>{selectedLog.fingerprint}</Text>
                  </div>
                  <div className="detail-item">
                    <strong>发生次数:</strong>
                    <Badge count={selectedLog.count} style={{ backgroundColor: '#f50' }} />
                  </div>
                  <div className="detail-item">
                    <strong>首次发现:</strong>
                    <span>{selectedLog.firstSeen}</span>
                  </div>
                  <div className="detail-item">
                    <strong>最后发现:</strong>
                    <span>{selectedLog.lastSeen}</span>
                  </div>
                  <div className="detail-item">
                    <strong>发生时间:</strong>
                    <span>{selectedLog.timestamp}</span>
                  </div>
                  <div className="detail-item">
                    <strong>错误级别:</strong>
                    <Tag color={getLevelColor(selectedLog.level)}>
                      {selectedLog.level.toUpperCase()}
                    </Tag>
                  </div>
                  <div className="detail-item">
                    <strong>错误信息:</strong>
                    <Paragraph copyable>{selectedLog.message}</Paragraph>
                  </div>
                  <div className="detail-item">
                    <strong>来源位置:</strong>
                    <Text code>{selectedLog.source}</Text>
                  </div>
                  <div className="detail-item">
                    <strong>错误URL:</strong>
                    <Text code copyable>{selectedLog.url}</Text>
                  </div>
                  <div className="detail-item">
                    <strong>用户ID:</strong>
                    <Text>{selectedLog.userId || '未知'}</Text>
                  </div>
                  <div className="detail-item">
                    <strong>会话ID:</strong>
                    <Text code>{selectedLog.sessionId}</Text>
                  </div>
                  <div className="detail-item">
                    <strong>IP地址:</strong>
                    <Text>{selectedLog.ip_address}</Text>
                  </div>
                  <div className="detail-item">
                    <strong>用户代理:</strong>
                    <Paragraph copyable ellipsis={{ rows: 2, expandable: true }}>
                      {selectedLog.user_agent}
                    </Paragraph>
                  </div>
                </div>
              </TabPane>
              
              <TabPane tab="堆栈跟踪" key="stack">
                {selectedLog.stack_trace ? (
                  <div className="detail-item">
                    <Paragraph copyable>
                      <pre className="stack-trace">{selectedLog.stack_trace}</pre>
                    </Paragraph>
                  </div>
                ) : (
                  <Empty description="暂无堆栈跟踪信息" />
                )}
              </TabPane>
              
              <TabPane tab="环境信息" key="environment">
                <div className="detail-section">
                  <Row gutter={[16, 16]}>
                    <Col span={12}>
                      <Card size="small" title="运行环境">
                        {selectedLog.environment ? (
                          <>
                            <p><strong>操作系统:</strong> {selectedLog.environment.os || '未知'}</p>
                            <p><strong>浏览器:</strong> {selectedLog.environment.browser || '未知'}</p>
                            <p><strong>设备类型:</strong> {selectedLog.environment.device || '未知'}</p>
                            <p><strong>用户代理:</strong></p>
                            <Paragraph copyable ellipsis={{ rows: 2, expandable: true }}>
                              {selectedLog.user_agent || '未知'}
                            </Paragraph>
                          </>
                        ) : (
                          <>
                            <p><strong>用户代理:</strong></p>
                            <Paragraph copyable ellipsis={{ rows: 2, expandable: true }}>
                              {selectedLog.user_agent || '未知'}
                            </Paragraph>
                            <p><strong>IP地址:</strong> {selectedLog.ip_address || '未知'}</p>
                            <p><strong>访问URL:</strong></p>
                            <Text code copyable>{selectedLog.url || '未知'}</Text>
                          </>
                        )}
                      </Card>
                    </Col>
                    <Col span={12}>
                      <Card size="small" title="应用信息">
                        {selectedLog.environment ? (
                          <>
                            <p><strong>应用版本:</strong> {selectedLog.environment.version || '未知'}</p>
                            <p><strong>构建信息:</strong> {selectedLog.environment.buildInfo || '未知'}</p>
                            <p><strong>部署环境:</strong> {selectedLog.environment.deployEnv || '未知'}</p>
                          </>
                        ) : (
                          <>
                            <p><strong>用户ID:</strong> {selectedLog.user_id || '未知'}</p>
                            <p><strong>会话ID:</strong></p>
                            <Text code>{selectedLog.session_id || '未知'}</Text>
                            <p><strong>项目:</strong> {selectedLog.project_name || '未知'}</p>
                          </>
                        )}
                      </Card>
                    </Col>
                  </Row>
                  
                  {selectedLog.request_info && (
                    <Card size="small" title="请求信息" style={{ marginTop: 16 }}>
                      <p><strong>请求方法:</strong> {selectedLog.request_info.method}</p>
                      <p><strong>请求URL:</strong> {selectedLog.request_info.url}</p>
                      <p><strong>响应状态:</strong> {selectedLog.request_info.responseStatus}</p>
                      <p><strong>响应时间:</strong> {selectedLog.request_info.responseTime}ms</p>
                      {selectedLog.request_info.params && (
                        <Collapse>
                          <Panel header="请求参数" key="params">
                            <pre>{JSON.stringify(selectedLog.request_info.params, null, 2)}</pre>
                          </Panel>
                        </Collapse>
                      )}
                      {selectedLog.request_info.headers && (
                        <Collapse>
                          <Panel header="请求头" key="headers">
                            <pre>{JSON.stringify(selectedLog.request_info.headers, null, 2)}</pre>
                          </Panel>
                        </Collapse>
                      )}
                    </Card>
                  )}
                </div>
              </TabPane>
              
              <TabPane tab="上下文" key="context">
                <div className="detail-section">
                  {selectedLog.context ? (
                    <Collapse>
                      {selectedLog.context.variables && (
                        <Panel header="变量状态" key="variables">
                          <pre>{JSON.stringify(selectedLog.context.variables, null, 2)}</pre>
                        </Panel>
                      )}
                      {selectedLog.context.state && (
                        <Panel header="组件状态" key="state">
                          <pre>{JSON.stringify(selectedLog.context.state, null, 2)}</pre>
                        </Panel>
                      )}
                      {selectedLog.context.props && (
                        <Panel header="组件属性" key="props">
                          <pre>{JSON.stringify(selectedLog.context.props, null, 2)}</pre>
                        </Panel>
                      )}
                    </Collapse>
                  ) : (
                    <Empty description="暂无上下文信息" />
                  )}
                </div>
              </TabPane>
            </Tabs>
          </div>
        )}
      </Drawer>

      {/* 告警配置模态框 */}
      <Modal
        title="告警配置"
        open={alertModalVisible}
        onCancel={() => setAlertModalVisible(false)}
        footer={null}
        width={800}
      >
        {renderAlertConfig()}
      </Modal>
    </div>
  );
};

export default ErrorLogs;